﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Seagull.Model.Stat
{
    // TODO: Change usage style to one-time-use tool.
    public class StatisticsViewer
    {
        public TimeSpan ZoomInterval { get; set; }

        public DateTime StartTime { get; set; }

        public Statistic[] FrameStatistics { get; set; }

        public IEnumerable<TimeStatistic> ZoomedStatistics
        {
            get
            {
                var interval = (int)(ZoomInterval.TotalSeconds * FrameSet.DefaultFrameCount);
                var startTime = StartTime;
                var counter = 0;
                byte max = 0;
                var sum = 0L;
                foreach(var frameStatistic in FrameStatistics)
                {
                    if(frameStatistic.Max > max)
                    {
                        max = frameStatistic.Max;
                    }
                    sum += frameStatistic.Avg;
                    if(++counter % interval == 0)
                    {
                        yield return
                            new TimeStatistic(
                                startTime.AddMilliseconds(FrameSet.DefaultNormalFrameSpaceMilliseconds * counter),
                                new Statistic(max, (byte)Math.Round(sum * 1.0 / interval)));
                        max = 0;
                        sum = 0;
                    }
                }
            }
        }

        public IEnumerable<TimeStatistic> GetStatisticsWithin(DateTime rangeStartTime, TimeSpan range)
        {
            var index = (int)((rangeStartTime - StartTime).TotalSeconds * FrameSet.DefaultFrameCount);
            var count = (int)(range.TotalSeconds * FrameSet.DefaultFrameCount);
            return FrameStatistics.Skip(index).Take(count).Select((stat, i) =>
                new TimeStatistic(rangeStartTime.AddMilliseconds(FrameSet.DefaultNormalFrameSpaceMilliseconds * i), stat));
        }
    }
}
